/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.orm.config;

import com.jfast.framework.kit.StrKit;
import com.jfast.framework.orm.TableInfo;
import com.jfast.framework.orm.annotation.Column;
import com.jfast.framework.orm.annotation.Table;
import com.jfast.framework.util.ClassScanner;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TableMapping {
	
	private List<TableInfo> tableList = new ArrayList<>();
	private Map<Class<?>, TableInfo> tableMap = new HashMap<>();
	private DataSourceConfig dataSourceConfig;

	public Map<Class<?>, TableInfo> getTableMap() {
		return tableMap;
	}
	
	public String getConfigName() {
		return dataSourceConfig.getName();
	}
	public TableMapping(DataSourceConfig dataSourceConfig){
		this.dataSourceConfig = dataSourceConfig;
	}
	
	public TableInfo getTableInfo(Class<?> tableClass){
		return getTableMap().get(tableClass);
	}

	public List<TableInfo> getTableList() {
		return tableList;
	}

	public void initTableMapping() {
		String basePackage = dataSourceConfig.getBasePackage();
        List<Class<?>> tableClass = null;
        if (StrKit.isEmpty(basePackage)) {
        	tableClass = ClassScanner.getClassByAnnoation(Table.class);
        } else {
        	tableClass = ClassScanner.getClassByAnnoation(Table.class, basePackage);
        }
		for (Class<?> clazz : tableClass) {
			Field[] fields = clazz.getDeclaredFields();
			Map<String,String> columnMapping = new HashMap<String,String>();
			for (Field field : fields) {
				field.setAccessible(true);
				Column column = field.getAnnotation(Column.class);
				if (StrKit.isNotEmpty(column) && StrKit.isNotEmpty(column.name())) {
					columnMapping.put(field.getName(), column.name());
				} else {
					columnMapping.put(field.getName(), field.getName());
				}
			}
			Table table = clazz.getAnnotation(Table.class);
			String tableName = table.name();
			String[] primaryKey = table.primaryKey();
			tableMap.put(clazz, new TableInfo(tableName, primaryKey, clazz, columnMapping));
		}
	}
}
